﻿using AutoMapper;
using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Image;
using MediatR;
using NuGet.Protocol.Plugins;

namespace B.S.Database.Write.Api.Application.CommandHandler.Image
{
    public class PictureCreateCommandHandler : IRequestHandler<PictureCreateCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Picture_Information> pictureRepo;
        private readonly IMapper mapper;

        public PictureCreateCommandHandler(IBaseResotity<Picture_Information> PictureRepo,IMapper mapper)
        {
            pictureRepo = PictureRepo;
            this.mapper = mapper;
        }
        public Task<Apiresult<object>> Handle(PictureCreateCommands request, CancellationToken cancellationToken)
        {
            Apiresult<object> res = new Apiresult<object>();
            
            try
            {
                // 检查是否已存在相同 TraceabilityId 的记录
                var existingPicture = pictureRepo.GetAll().FirstOrDefault(x => x.TraceabilityId == request.TraceabilityId);
                
                if (existingPicture != null)
                {
                    // 如果存在，根据追加模式处理
                    if (request.IsAppend)
                    {
                        // 追加模式：将新内容追加到现有内容后面
                        existingPicture.Inspection_Repor = AppendString(existingPicture.Inspection_Repor, request.Inspection_Repor, request.Separator);
                        existingPicture.Livestock_Certification = AppendString(existingPicture.Livestock_Certification, request.Livestock_Certification, request.Separator);
                        existingPicture.Certification_Documents = AppendString(existingPicture.Certification_Documents, request.Certification_Documents, request.Separator);
                        existingPicture.Food_Safety = AppendString(existingPicture.Food_Safety, request.Food_Safety, request.Separator);
                        existingPicture.Raw_Material = AppendString(existingPicture.Raw_Material, request.Raw_Material, request.Separator);
                        existingPicture.Auxiliary_Materials = AppendString(existingPicture.Auxiliary_Materials, request.Auxiliary_Materials, request.Separator);
                        existingPicture.Additive_Materials = AppendString(existingPicture.Additive_Materials, request.Additive_Materials, request.Separator);
                        existingPicture.Packaging_Materials = AppendString(existingPicture.Packaging_Materials, request.Packaging_Materials, request.Separator);
                        existingPicture.Enterprise_Image = AppendString(existingPicture.Enterprise_Image, request.Enterprise_Image, request.Separator);
                        pictureRepo.Update(existingPicture);
                        res.Code = ApiEnums.成功;
                        res.Message = "图片信息追加成功";
                    }
                    else
                    {
                        // 覆盖模式：直接替换现有内容
                        existingPicture.Inspection_Repor = ConvertListToString(request.Inspection_Repor, request.Separator);
                        existingPicture.Livestock_Certification = ConvertListToString(request.Livestock_Certification, request.Separator);
                        existingPicture.Certification_Documents = ConvertListToString(request.Certification_Documents, request.Separator);
                        existingPicture.Food_Safety = ConvertListToString(request.Food_Safety, request.Separator);
                        existingPicture.Raw_Material = ConvertListToString(request.Raw_Material, request.Separator);
                        existingPicture.Auxiliary_Materials = ConvertListToString(request.Auxiliary_Materials, request.Separator);
                        existingPicture.Additive_Materials = ConvertListToString(request.Additive_Materials, request.Separator);
                        existingPicture.Packaging_Materials = ConvertListToString(request.Packaging_Materials, request.Separator);
                        existingPicture.Enterprise_Image = ConvertListToString(request.Enterprise_Image, request.Separator);
                        pictureRepo.Update(existingPicture);
                        res.Code = ApiEnums.成功;
                        res.Message = "图片信息覆盖成功";
                    }
                }
                else
                {
                    // 如果不存在，则添加新记录
                    var newPicture = new Picture_Information
                    {
                        TraceabilityId = request.TraceabilityId,
                        Inspection_Repor = ConvertListToString(request.Inspection_Repor, request.Separator),
                        //Livestock_Certification = ConvertListToString(request.Livestock_Certification, request.Separator),
                        //Certification_Documents = ConvertListToString(request.Certification_Documents, request.Separator),
                        //Food_Safety = ConvertListToString(request.Food_Safety, request.Separator),
                        //Raw_Material = ConvertListToString(request.Raw_Material, request.Separator),
                        //Auxiliary_Materials = ConvertListToString(request.Auxiliary_Materials, request.Separator),
                        //Additive_Materials = ConvertListToString(request.Additive_Materials, request.Separator),
                        //Packaging_Materials = ConvertListToString(request.Packaging_Materials, request.Separator),
                        //Enterprise_Image = ConvertListToString(request.Enterprise_Image, request.Separator)
                    };
                    
                    pictureRepo.Add(newPicture);
                    res.Code = ApiEnums.成功;
                    res.Message = "图片信息添加成功";
                }
            }
            catch (Exception ex)
            {
                res.Code = ApiEnums.失败;
                res.Message = $"图片信息操作失败: {ex.Message}";
            }
            
            return Task.FromResult(res);
        }

        /// <summary>
        /// 将字符串列表转换为分隔符连接的字符串
        /// </summary>
        /// <param name="list">字符串列表</param>
        /// <param name="separator">分隔符</param>
        /// <returns>连接后的字符串</returns>
        private string ConvertListToString(List<string>? list, string separator)
        {
            if (list == null || !list.Any())
                return null;
            
            return string.Join(separator, list.Where(x => !string.IsNullOrEmpty(x)));
        }

        /// <summary>
        /// 追加字符串的辅助方法
        /// </summary>
        /// <param name="existingValue">现有值</param>
        /// <param name="newValues">新值列表</param>
        /// <param name="separator">分隔符</param>
        /// <returns>追加后的字符串</returns>
        private string AppendString(string existingValue, List<string> newValues, string separator)
        {
            if (newValues == null || !newValues.Any())
                return existingValue;
            
            string newValueString = ConvertListToString(newValues, separator);
            
            if (string.IsNullOrEmpty(newValueString))
                return existingValue;
            
            if (string.IsNullOrEmpty(existingValue))
                return newValueString;
            
            return $"{existingValue}{separator}{newValueString}";
        }
    }
}
